package cn.zzdt4j.core.executor.support.service;

import cn.zzdt4j.common.executor.support.BlockingQueueTypeEnum;
import cn.zzdt4j.common.executor.support.RejectedPolicyTypeEnum;
import cn.zzdt4j.common.model.register.DynamicThreadPoolRegisterParameter;
import cn.zzdt4j.core.executor.support.ThreadPoolBuilder;

import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Abstract dynamic thread-pool service.
 *
 * @author by <a href="mailto:ligang941012@gmail.com">gang.Li</a>
 * @since 2024/5/14 0:45
 */
public abstract class AbstractDynamicThreadPoolService implements DynamicThreadPoolService {

    /**
     * Build dynamic thread-pool executor.
     *
     * @param registerParameter the register parameter
     * @return the thread pool executor
     */
    public ThreadPoolExecutor buildDynamicThreadPoolExecutor(DynamicThreadPoolRegisterParameter registerParameter) {
        return ThreadPoolBuilder.builder()
                .threadPoolId(registerParameter.getThreadPoolId())
                .corePoolSize(registerParameter.getCorePoolSize())
                .maximumPoolSize(registerParameter.getMaximumPoolSize())
                .workQueue(BlockingQueueTypeEnum.createBlockingQueue(registerParameter.getBlockingQueueType().getType(), registerParameter.getCapacity()))
                .threadFactory(registerParameter.getThreadNamePrefix())
                .threadFactory(registerParameter.getThreadFactory())
                .keepAliveTime(registerParameter.getKeepAliveTime(), TimeUnit.SECONDS)
                .executeTimeOut(registerParameter.getExecuteTimeOut())
                .rejected(RejectedPolicyTypeEnum.createPolicy(registerParameter.getRejectedPolicyType().getType()))
                .dynamicPool()
                .build();
    }
}
